package org.bunny.vehicle.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.bunny.vehicle.entity.User;

public class PageFilter implements Filter {

	static final String RESOURCE_DIR = "resources";

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		String requestUri = StringUtils.substringAfter(httpRequest.getRequestURI(),
				httpRequest.getContextPath() + "/");
		if (StringUtils.startsWithIgnoreCase(requestUri, RESOURCE_DIR)) {
			chain.doFilter(request, response);
			return;
		}

		HttpSession session = httpRequest.getSession(false);

		if (null != session && null != session.getAttribute(Const.SESSION_USER)) {
			User user = (User) session.getAttribute(Const.SESSION_USER);
			httpRequest.setAttribute("user", user);
		}

		httpRequest.getRequestDispatcher(requestUri + ".jsp").forward(httpRequest, response);

		try {
			chain.doFilter(httpRequest, response);
		} catch (IllegalStateException e) {
		}
	}

	@Override
	public void destroy() {

	}

}
